package me.jzn.alib.custom.uri;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.Map;

import me.jzn.core.exceptions.ShouldNotRunHereException;
import me.jzn.core.utils.CommUtil;
import me.jzn.core.utils.StrUtil;

public class ActivityUri implements BaseCustomUri {
    private static final String SCHEME = BaseCustomUri.SCHEME_ACTIVITY;
    private Uri mUri;

    public ActivityUri(Uri uri) {
        if (!BaseCustomUri.SCHEME_ACTIVITY.equals(uri.getScheme())) {
            throw new IllegalArgumentException("ActivityUri的scheme必须是" + SCHEME);
        }
        mUri = uri;
    }

    public ActivityUri(String className, @Nullable String queryStringUrlEncoded) {
        _checkActivityClass(className);

        String uriString = null;
        if (queryStringUrlEncoded != null && queryStringUrlEncoded.length() > 0) {
            uriString = String.format("%s://%s?%s", SCHEME, className, queryStringUrlEncoded);
        } else {
            uriString = String.format("%s://%s", SCHEME, className);
        }
        mUri = Uri.parse(uriString);
    }


    public ActivityUri(Class<? extends Activity> cls) {
        this(cls, null);
    }

    /**
     * 目前参数只支持string类型
     */
    public ActivityUri(Class<? extends Activity> cls, Map<String, ?> params) {
        this(cls.getCanonicalName(), params);
    }

    public ActivityUri(String className, Map<String, ?> params) {
        _checkActivityClass(className);
        StringBuilder querySb = null;
        if (params != null) {
            querySb = new StringBuilder();
            for (Map.Entry<String, ?> entry : params.entrySet()) {
                String keyEncoded = StrUtil.urlEnc(entry.getKey(), StrUtil.UTF8);
                Object value = entry.getValue();
                if (value != null) {
                    String valueEncoded = StrUtil.urlEnc(value.toString(), StrUtil.UTF8);
                    querySb.append(keyEncoded).append('=').append(valueEncoded).append("&");
                }
            }
        }
        String uriString = null;
        if (querySb == null || querySb.length() == 0) {
            uriString = String.format("%s://%s", SCHEME, className);
        } else {
            uriString = String.format("%s://%s?%s", SCHEME, className, querySb.deleteCharAt(querySb.length() - 1));
        }
        mUri = Uri.parse(uriString);
    }

    public Class<? extends Activity> getTgtClass() {
        try {
            return (Class<? extends Activity>) Class.forName(mUri.getAuthority());
        } catch (ClassNotFoundException e) {
            throw new ShouldNotRunHereException(e);
        }
    }

    public Intent toIntent(Context ctx) {
        Intent intent = new Intent();
        intent.setClassName(ctx, mUri.getAuthority());
        for (String key : mUri.getQueryParameterNames()) {
            intent.putExtra(key, mUri.getQueryParameter(key));
        }
        return intent;
    }

    @NonNull
    @Override
    public String toString() {
        return mUri.toString();
    }

    @Override
    public String getScheme() {
        return SCHEME;
    }

    private void _checkActivityClass(String className) {
        try {
            Class<?> clz = Class.forName(className, false, ActivityUri.class.getClassLoader());
            if (!CommUtil.isSubClass(clz, Activity.class)) {
                throw new IllegalArgumentException("不是activity的子类:" + className);
            }
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("找不到activity:" + className);
        }
    }
}
